const cryptoUtils = require('../utils/crypto');
module.exports = (app) => {
  let message = '无效的access_token';
  const mixin = app.config.mixin || {};
  return async function authroization(ctx, next) {
    let accessToken = ctx.get('Authorization') || ctx.get('authorization');
    console.log(accessToken)
    if (!accessToken){
      const userInfo = ctx.session.user || {};
      accessToken = userInfo.access_token;
      ctx.throw(10002, message)
    }

    try {
      const data = JSON.parse(cryptoUtils.decryptAes('aes-128-ecb', mixin.aesKey, '', accessToken));
      if (!data) {
        ctx.throw(10003, message)
      }
      // 这里做权限验证
      let roles = [];
      if (Array.isArray(roles) && roles.length) {
        let hasAccess = false;
        if (roles.includes(data.role_id)) {
          hasAccess = true;
        }
        if (hasAccess) {
          await next();
        } else {
          ctx.throw(10005)
        }
      } else {
        await next();
      }
    } catch (error) {
      ctx.throw(401, error.message || '没有登录');
    }
  };
}
